//
//  StoreEditStore.swift
//  Share
//
//  Created by admin on 2020/12/18.
//  Copyright © 2020 MBA. All rights reserved.
//
import Combine
import Foundation
import SwiftUI

class StoreEditStore: ObservableObject {
    
    @Published var store:Store?
    @Published var num:String = ""
    @Published var price:String = ""
    @Published var day:String = ""
    @Published var state:String = ""
    @Published var outprice:String = ""
    @Published var outday:String = ""
    @Published var fee:String = ""
    
    @Published var tostError:TostError?
    
    
    var id:Int?
    var shareId:Int
    init(id:Int,shareId:Int) {
        self.id = id
        self.shareId = shareId
        self.update()
      
    }

    /**
      更新store
     */
    func update()  {
        if (id != 0) {
            Store.db_store(storeId: id!) { (error, store) in
                if error == nil{
                    self.store = store ?? Store()
                    self.reloadData()
                }else{
//                    self.error = true
                }
            }
        }
    }
    
    func reloadData() {
        self.num = "\(store!.num)"
        self.price = "\(store!.price)"
        self.day = "\(store!.day ?? "--")"
        self.state = "\(store!.state ?? 0)"
        self.outday = store!.outday ?? "0"
        self.outprice = "\(store!.outprice ?? 0)"
        self.fee = "\(store!.fee ?? 0)"


    }

    func save(finesh:@escaping  (Error?) ->  ()) {

        var tstore = Store()
        if id != nil {
            tstore.id = id!
            tstore.share_id = self.shareId
        }
        
        tstore.num = Int(num) ?? 0
        tstore.day = day
        tstore.price = Float(price) ?? 0.0
        tstore.state = Int(state)
        tstore.outday = outday
        tstore.outprice = Float(outprice) ?? 0.0
        tstore.fee = Float(fee) ?? 0.0
        tstore.db_store(id: tstore.id) { (error, store) in
         
            if error == nil{
                self.update()
            }
            finesh(error)
        }
        
        
    }

    
    func delete(finesh:@escaping  (Error?) ->  ()) throws{
        guard let hstore:Store = store else {
            throw TostError.init(code: -1, msg: "错误", title: "store不能为nil", level: .error)
        }
        
        hstore.delete(finesh: finesh)

    }

    

    
}

